﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Vowei.Core;
using Vowei.Core.Models;
using Vowei.Data;
using Vowei.Data.Helpers;
using Vowei.Data.Models;
using Vowei.Web.Helpers;
using System.Collections;
using Vowei.Web.Models;
using Vowei.Data.Converters.Excel;
using System.IO;

namespace Vowei.Web.Controllers
{
    [HandleError]
    [Authorize]
    public class RequirementController : TicketControllerBase<Requirement>
    {
        public RequirementController(IVoweiContext context, IUser user) : base(context, user) { }

        protected override List<Requirement> ResortOfProxy(IEnumerable<Requirement> table)
        {
            var result = new List<Requirement>();

            foreach (var r in table)
            {
                result.Add(new Requirement()
                {
                    ID = r.ID,
                    Title = r.Title,
                    AssignedTo = r.AssignedTo,
                    BusinessValue = r.BusinessValue,
                    ClosedDate = r.ClosedDate,
                    Description = r.Description,
                    BelongsToMilestone = r.BelongsToMilestone,
                    OpenDate = r.OpenDate,
                    Reporter = r.Reporter
                });
            }

            return result;
        }

        protected override ActionResult DetailsImpl(Guid id)
        {
            var result = base.DetailsImpl(id) as ViewResult;

            ViewData["UpRequirement"] = ((Requirement)result.Model).GetUpRequirement(Context);

            return result;
        }

        protected override ActionResult EditImpl(Guid? id)
        {
            var ticket = EntityHelpers.GenericGetObjectDetails<Requirement>(id, Context);
            var milestones = new ArrayList();

            if (ticket.BelongsToMilestoneId.HasValue)
                ticket.BelongsToMilestone = (Milestone)Context.Milestones.Find(ticket.BelongsToMilestoneId);

            if (ticket.BelongsToMilestone == null)
            {
                var results = from m in Context.Milestones.Query
                              select new { m.ID, m.Title };

                foreach (var item in results)
                {
                    milestones.Add(item);
                }
            }
            else
            {
                var mid = ticket.BelongsToMilestone.ID;
                var project = Context.Milestones.Include("BelongsToMilestone").Query.First(m => m.ID == mid);
                // TODO: 下面这个循环改成一个存储过程吧，要查询数据库几次
                while (project.BelongsToMilestone != null)
                {
                    mid = project.BelongsToMilestone.ID;
                    project = Context.Milestones.Include("BelongsToMilestone").Query.First(m => m.ID == mid);
                }

                // 把项目添加进去
                milestones.Add(project);
                foreach (var item in project.AllMilestones(Context))
                    milestones.Add(item);

                ViewData["ProjectId"] = project.ID;
            }

            ViewData["Milestones"] = ViewHelpers.SerializeToJson(milestones);
            return View("Edit", ticket).AddJsonSupport();
        }

        protected override ActionResult EditImpl(Requirement requirement)
        {
            if (requirement.BelongsToMilestone != null)
                ((IScoped)requirement).BelongsToMilestone = Context.Milestones.Find(requirement.BelongsToMilestone.ID);
            else if (requirement.BelongsToMilestoneId != Guid.Empty)
                ((IScoped)requirement).BelongsToMilestone = Context.Milestones.Find(requirement.BelongsToMilestoneId);
            else
                throw new InvalidOperationException(string.Format(T("正在尝试新建的需求 {0} 没有指定里程碑！"), requirement.Title));

            var children = requirement.Children.ToArray();
            requirement.Children.Clear();
            foreach (var ticket in children)
            {
                requirement.Children.Add((Ticket)Context.Tickets.Find(ticket.ID));
            }

            EditingHelpers.GenericEndEdit(requirement, Context, CurrentUser);

            // TODO: 看看如何把这些小的补丁整合成一个通用的函数
            if (Request != null &&
                Request.AcceptTypes.Any(s => s == "application/json"))
            {
                var json = ViewHelpers.SerializeToJson(new
                {
                    requirement.ID,
                    requirement.Title
                });
                Response.Write(json);

                return WebConstants.HttpSuccess;
            }
            else
            {
                return RedirectToAction("Index", new { pid = requirement.BelongsToMilestone.ID });
            }
        }

        public ActionResult UnAssigned(Guid pid)
        {
            var milestone = Context.Milestones.Find(pid);
            Project project = null;

            // TODO: 这一块要加测试用例
            if (milestone is Project)
                project = milestone as Project;
            else
                project = milestone.GetBelongingProject(Context);

            var requirements = project.TopRequirements(Context);
            return JsonImpl(requirements.OfType<Requirement>());
        }

        public ActionResult AllTickets(Guid id)
        {
            var requirement = Context.Requirements.Find(id);
            if (requirement == null)
                throw new InvalidOperationException(string.Format(T("找不到id为[{0}]的需求！"), id));

            var tickets = requirement.AllTickets(Context);
            var list = tickets.ToArray();
            ViewBag.Title = string.Format(T("需求 [{0}] 里的所有子需求和任务！"), requirement.Title);

            return View(list);
        }
    }
}
